<template>
  <page-header-wrapper :title="false">
    <a-card title="会员列表">
      <template #extra>
        <a-tooltip>
          <template #title> 数据导出</template>
          <a-button type="primary" icon="database" @click="handleExpert(queryParam)"></a-button>
        </a-tooltip>
      </template>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="加入日期">
                <a-range-picker v-model="queryParam.date" format="YYYY-MM-DD" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="关键字">
                <a-input :value="value" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="标签">
                <a-select v-model="queryParam.mark">
                  <a-select-option :value="i.id" v-for="i in markOption" :key="i.id">{{ i.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="性别">
                  <a-select v-model="queryParam.sex">
                    <a-select-option value="1">男</a-select-option>
                    <a-select-option value="2">女</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="销售负责">
                  <a-select v-model="queryParam.empName">
                    <a-select-option :value="i.id" v-for="i in userOption" :key="i.id">{{
                      i.userName
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="微信">
                  <a-select v-model="queryParam.weiXin">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option value="0">未绑定</a-select-option>
                    <a-select-option value="1">已绑定</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" :loading="loading" @click="handleSearch(queryParam)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleCreate()">新增会员</a-button>
      </div>

      <a-table
        :loading="loading"
        size="default"
        rowKey="key"
        :scroll="{ x: 2400 }"
        :columns="columns"
        :data-source="loadData"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        
        <span slot="level" slot-scope="text, record">
          {{ record?.level == '0' ? '普卡' :'VIP' }}
        </span>
        
        <span slot="memLabelList" slot-scope="text, record">
          <template>
            {{ record.memLabelList.map((item)=>{ return item.name}).toString() }}
          </template>
        </span>
        <span slot="sex" slot-scope="text, record">
          <template>
            <div v-if="record.sex == '1'">男</div>
            <div v-if="record.sex == '2'">女</div>
          </template>
        </span>
        <span slot="status" slot-scope="text, record">
          <template>
            <a-tag color="#82af6f" v-if="record?.status == 1">启用中</a-tag>
            <a-tag color="#abbac3" v-else>已停用</a-tag>
          </template>
        </span>
        
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428bca" @click="handleDetail(record)">进入</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
  </page-header-wrapper>
</template>

<script>
import { getMemberListUsingPOST, addMemberUsingPOST, updateMemberUsingPOST,exportMemberListUsingPOST } from '@/api/api/huiyuanguanli.ts'
import { getEmployeesListUsingPOST } from '@/api/api/yuangongguanli.ts'
import { getMemLabelListUsingPOST } from '@/api/api/xitongguanli.ts'
import CreateForm from './CreateForm'
import moment from 'moment'
import { omit } from 'lodash-es'
export default {
  name: 'MemberListIndex',
  components: {
    CreateForm,
  },
  data() {
    return {
      mdl: null,
      priceMdl: null,
      visible: false,
      priceVisible: false,
      value: '',
      confirmLoading: false,
      priceLoading: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        // date: [moment().startOf('months').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
        date: null,
        status: '',
      },
      optionParam: {
        pageNo: 1,
        pageSize: 999,
        queryCondition: '',
        status: 1,
      },
      markOption: [],
      userOption: [],
      // 表头
      columns: [
        {
          title: '会员ID',
          dataIndex: 'id',
          width: 200,
        },
        {
          title: '会员姓名',
          dataIndex: 'name',
          width: 144,
        },
        {
          title: '会员卡号',
          dataIndex: 'cardNo',
          width: 144,
        },
        {
          title: '联系电话',
          dataIndex: 'phone',
          width: 120,
        },
        {
          title: '会员等级',
          dataIndex: 'level',
          scopedSlots: { customRender: 'level' },
          width: 100,
        },
        {
          title: '销售负责人',
          dataIndex: 'empName',
          width: 144,
        },
        {
          title: '归属店',
          dataIndex: 'storeName',
          width: 100,
        },
        {
          title: '标签',
          dataIndex: 'memLabelList',
          scopedSlots: { customRender: 'memLabelList' },
          width: 260,
        },
        {
          title: '加入日期',
          dataIndex: 'joinDate',
          width: 160,
        },
        {
          title: '性别',
          dataIndex: 'sex',
          scopedSlots: { customRender: 'sex' },
          width: 140,
        },
        {
          title: '生日',
          dataIndex: 'birthday',
          width: 160,
        },
        {
          title: '身份证号',
          dataIndex: 'idCardNo',
          width: 170,
        },
        {
          title: '当前积分',
          dataIndex: 'bigintegral',
        },
        {
          title: '历史积分',
          dataIndex: 'hisBigintegral',
        },
        {
          title: '绑定微信',
          dataIndex: 'weiXin',
        },
        {
          title: '是否关注',
          dataIndex: 'isCare',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 80,
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      loading: false,
      pagination: {},
      optionAlertShow: false,
    }
  },
  created() {
    this.getMarkOption()
    this.handleSearch(this.queryParam)
    this.getUserOption()
  },
  methods: {
    handleExpert(val){
      const params = {
        ...val,
        startTime: val?.date?.[0] ? moment(val?.date?.[0]).format('YYYY-MM-DD') : null,
        endTime: val?.date?.[1] ? moment(val?.date?.[1]).format('YYYY-MM-DD') : null,
      }
      exportMemberListUsingPOST({ ...omit(params, ['date']) }).then((res) => {
          const blob = new Blob([res], {
            type: 'application/vnd.ms-excel;charset=utf-8',
          })
          const filename = '会员列表' + '.xlsx'
          // 将blob对象转为一个URL
          var blobURL = window.URL.createObjectURL(blob)
          // 创建一个a标签
          var tempLink = document.createElement('a')
          // 隐藏a标签
          tempLink.style.display = 'none'
          // 设置a标签的href属性为blob对象转化的URL
          tempLink.href = blobURL
          // 给a标签添加下载属性
          tempLink.setAttribute('download', filename)
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 将a标签添加到body当中
          document.body.appendChild(tempLink)
          // 启动下载
          tempLink.click()
          // 下载完毕删除a标签
          document.body.removeChild(tempLink)
          window.URL.revokeObjectURL(blobURL)
          this.$message.success('导出成功~')
        })  
    },
    getMarkOption() {
      getMemLabelListUsingPOST(this.optionParam)
        .then((res) => {
          this.markOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },

    getUserOption() {
      getEmployeesListUsingPOST(this.optionParam)
        .then((res) => {
          this.userOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleSearch(val) {
      this.loading = true
      const params = {
        ...val,
        startTime: val?.date?.[0] ? moment(val?.date?.[0]).format('YYYY-MM-DD') : null,
        endTime: val?.date?.[1] ? moment(val?.date?.[1]).format('YYYY-MM-DD') : null,
      }
      getMemberListUsingPOST({ ...omit(params, ['date']) })
        .then((res) => {
          this.loadData = res.data.list
          this.loading = false
          this.queryParam.pageNo = this.pagination.current
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch((error) => {
          this.loading = false
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
 pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition: this.queryParam.queryCondition,
        status: this.queryParam.status,
        date: this.queryParam.date,
      })
    },
    handleCreate() {
      this.visible = true
    },
    handleDetail(record) {
      this.$router.push({ path: `/member/list/detail/${record.id}` })
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (!!values.id) {
            const params = {
              ...values,
              joinDate: values?.joinDate,
              birthday: values?.birthday,
            }
            // 修改 e.g.
            updateMemberUsingPOST(
              {...omit(params, ['mark']) },
              values.mark.map((i) => {
                return { labelId: i }
              })
            )
              .then(() => {
                this.handleSearch(this.queryParam)
                this.$message.success('操作成功')
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
              })
              .catch((error) => {
                this.confirmLoading = false
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          } else {
            if (!values.phone && !values.cardNo) {
              this.$message.warn('手机号、会员卡号，至少填写一个!')
              this.confirmLoading = false
              return false
            }
            const params = {
              ...values,
              joinDate: values?.joinDate ? moment(values?.joinDate).format('YYYY-MM-DD') : null,
              birthday: values?.birthday ? moment(values?.birthday).format('YYYY-MM-DD') : null,
            }
            // 新增
            addMemberUsingPOST({ ...params })
              .then(() => {
                this.handleSearch(this.queryParam)
                this.$message.success('操作成功')
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
              })
              .catch((error) => {
                this.confirmLoading = false
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },

    toggleAdvanced() {
      this.advanced = !this.advanced
    },
  },
}
</script>
